﻿using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YLW.Plat.Jhfw.HL7V3
{
    public class GzipHelper
    {
        //
        // 摘要:
        //     将传入字符串以GZip算法压缩后，返回Base64编码字符
        //
        // 参数:
        //   rawString:
        //     需要压缩的字符串
        //
        // 返回结果:
        //     压缩后的Base64编码的字符串
        public static string GZipCompressString(string rawString)
        {
            if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
            {
                return "";
            }

            return Convert.ToBase64String(Compress(Encoding.UTF8.GetBytes(rawString.ToString())));
        }

        //
        // 摘要:
        //     GZip压缩
        //
        // 参数:
        //   rawData:
        public static byte[] Compress(byte[] rawData)
        {
            MemoryStream memoryStream = new MemoryStream();
            GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, leaveOpen: true);
            gZipStream.Write(rawData, 0, rawData.Length);
            gZipStream.Close();
            return memoryStream.ToArray();
        }

        //
        // 摘要:
        //     将传入的二进制字符串资料以GZip算法解压缩
        //
        // 参数:
        //   zippedString:
        //     经GZip压缩后的二进制字符串
        //
        // 返回结果:
        //     原始未压缩字符串
        public static string GZipDecompressString(string zippedString)
        {
            if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)
            {
                return "";
            }

            byte[] zippedData = Convert.FromBase64String(zippedString.ToString());
            return Encoding.UTF8.GetString(Decompress(zippedData));
        }

        //
        // 摘要:
        //     ZIP解压
        //
        // 参数:
        //   zippedData:
        public static byte[] Decompress(byte[] zippedData)
        {
            GZipStream gZipStream = new GZipStream(new MemoryStream(zippedData), CompressionMode.Decompress);
            MemoryStream memoryStream = new MemoryStream();
            byte[] array = new byte[1024];
            while (true)
            {
                int num = gZipStream.Read(array, 0, array.Length);
                if (num <= 0)
                {
                    break;
                }

                memoryStream.Write(array, 0, num);
            }

            gZipStream.Close();
            return memoryStream.ToArray();
        }
    }
}
